<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="70px">
      <el-form-item :label="t('trend.model_id')">
        <el-select
          v-model="form.model_id"
          :filterable="true"
          :placeholder="t('supply.model_id')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in modelList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('trend.seller_id')">
        <el-select
          v-model="form.seller_id"
          :filterable="true"
          :placeholder="t('supply.seller_id')"
          :clearable="false"
          multiple
          style="width: 250px"
        >
          <el-option
            v-for="item in sellerList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('trend.time')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          format="YYYY/MM/DD"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changeTime"
          :editable="false"
          unlink-panels
        />
      </el-form-item>

      <el-form-item :label="t('trend.inventory_status')">
        <el-select
          v-model="form.inventory_status"
          :filterable="true"
          :placeholder="t('trend.inventory_status')"
          :clearable="false"
          style="width: 250px"
        >
          <el-option
            v-for="item in inventoryStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('trend.presale_time')">
        <el-date-picker
          v-model="form.presale_time"
          type="daterange"
          format="YYYY/MM/DD"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          @change="changePresaleTime"
          :editable="false"
          unlink-panels
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initQuery">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div v-if="type === 'candlestick' && categories_offer.length > 0">
      <!--      报价-->
      <KLineChart :kLineData="offerData" :categoryData="categories_offer" name="售价趋势" />
    </div>
    <div v-if="type === 'candlestick' && categories_cash.length > 0">
      <!--      现价-->
      <KLineChart :kLineData="cashData" :categoryData="categories_cash" name="报价趋势" />
    </div>
    <div v-if="type === 'line' && categories.length > 0">
      <!--      折线图-->
      <LineChart :seriesData="foldData" :categoryData="categories" name="折线趋势" />
    </div>
    <div class="flex justify-between">
      <div class="table-container flex-none mr-20px" v-if="dataList.length > 0">
        <el-table
          :data="dataList"
          highlight-current-row
          stripe
          border
          :fit="true"
          size="small"
          v-loading="tableLoading"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
        >
          <el-table-column prop="0" />
          <el-table-column :label="t('trend.price')" prop="1" :show-overflow-tooltip="true" />
          <el-table-column :label="t('trend.seller_id')" prop="2" :show-overflow-tooltip="true" />
          <el-table-column :label="t('trend.create_time')" prop="3" :show-overflow-tooltip="true" />
        </el-table>
      </div>

      <div class="w-[calc(50%-20px)]" v-if="priceTrendList.length > 0">
        <el-table
          :data="priceTrendList"
          highlight-current-row
          stripe
          border
          :fit="true"
          size="small"
          v-loading="tableLoading"
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center' }"
        >
          <el-table-column
            :label="t('trend.seller_id')"
            prop="seller_name"
            :show-overflow-tooltip="true"
          />
          <el-table-column :label="t('trend.price')" :show-overflow-tooltip="true">
            <template #default="{ row }"> {{ row.price }}({{ row.price_unit }}) </template>
          </el-table-column>
          <el-table-column
            :label="t('trend.create_time')"
            prop="create_time"
            :show-overflow-tooltip="true"
          />
        </el-table>
      </div>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { ElButton } from 'element-plus'
import { getGoodsEnumApi, getEchartsApi, getPriceTrendApi } from '@/api/trend'
import KLineChart from './Kline/Page.vue'
import LineChart from './FoldLine/Page.vue'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'

const { query } = useRoute()

const { t } = useI18n()

const tableLoading = ref<boolean>(false)
const dataList = ref<Array<Record<string, any>>>([])

const modelList = ref<Array<Record<string, any>>>([])
const sellerList = ref<Array<Record<string, any>>>([])
const inventoryStatusList = ref<Array<Record<string, any>>>([])
const priceCategoryList = ref<Array<Record<string, any>>>([])
const sellerCategoryList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])

const form = ref<Record<string, any>>({
  start_date: '',
  end_date: '',
  seller_id: [],
  pageIndex: 1,
  pageSize: 15,
  presale_start_date: '',
  presale_end_date: ''
})

const categories = ref<Array<Record<string, any>>>([])
const categories_offer = ref<Array<Record<string, any>>>([])
const categories_cash = ref<Array<Record<string, any>>>([])
const offerData = ref<Array<Array<number>>>([])
const cashData = ref<Array<Array<number>>>([])
const type = ref<string>('')

const foldData = ref<Array<Record<string, any>>>([])

//初始化请求
const initialize = async () => {
  // tableLoading.value = true
  // const params = JSON.parse(JSON.stringify(form.value))
  // delete params.date
  //
  // const tableData = await getListApi(params)
  // dataList.value = tableData?.data?.list
  // paginationTotal.value = tableData?.data?.total
  // tableLoading.value = false
}

const getPastYearStartAndEnd = () => {
  const today = new Date()

  // 获取一年前的日期，并保持同一时间
  const yearAgo = new Date(today)
  yearAgo.setFullYear(today.getFullYear() - 1)

  // 返回去年同一日期，并将当前时间设置为开始时间
  const startDate = new Date(yearAgo.getTime() + 1000)

  // 将当前时间设置为今天的结束时间
  const endDate = new Date(today)

  return {
    startDate: formatDateWithTime(startDate),
    endDate: formatDateWithTime(endDate)
  }
}
const formatDateWithTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day}`
}

const priceTrendList = ref([])
// 初始化折线图和K线图数据
const initLine = async () => {
  tableLoading.value = true

  let obj = JSON.parse(JSON.stringify(form.value))
  // delete obj.start_date
  // delete obj.end_date
  const rrr = await getPriceTrendApi(obj)
  priceTrendList.value = rrr.data || []
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  delete params.presale_time
  const resp = await getEchartsApi(params)

  if (resp?.data?.type === 'line') {
    foldData.value = resp.data?.data?.data
    categories.value = resp?.data?.data?.date_line ?? []
  } else if (resp?.data?.type === 'candlestick') {
    offerData.value = resp.data.data.offer_data
    cashData.value = resp.data.data.cash_data
    categories_offer.value = resp?.data?.data?.offer_date_line ?? []
    categories_cash.value = resp?.data?.data?.cash_date_line ?? []
  }
  type.value = resp?.data?.type
  dataList.value = resp?.data?.data.statistics ?? []
  tableLoading.value = false
}

//查询
const initQuery = () => {
  initLine()
}

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_date = dayjs(e[0]).format('YYYY-MM-DD')
    form.value.end_date = dayjs(e[1]).format('YYYY-MM-DD')
  } else {
    form.value.start_date = null
    form.value.end_date = null
  }
}

const changePresaleTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.presale_start_date = dayjs(e[0]).format('YYYY-MM-DD')
    form.value.presale_end_date = dayjs(e[1]).format('YYYY-MM-DD')
  } else {
    form.value.presale_start_date = null
    form.value.presale_end_date = null
  }
}

//重置查询项
const reset = () => {
  form.value = {
    start_date: '',
    end_date: '',
    seller_id: [],
    pageIndex: 1,
    pageSize: 15,
    presale_start_date: '',
    presale_end_date: ''
  }
  initLine()
}

const getDropDownBoxInfo = async () => {
  const resp = await getGoodsEnumApi({ field: 'all' })
  sellerList.value = resp.data.seller
  inventoryStatusList.value = resp.data.inventory_status
  priceCategoryList.value = resp.data.price_category
  sellerCategoryList.value = resp.data.seller_category
  statusList.value = resp.data.status
  modelList.value = resp.data.model
}

onMounted(() => {
  // 获取 URL 参数中的日期范围，如果存在的话
  const startDateFromQuery = query?.startDate ? dayjs(query.startDate as string) : null
  const endDateFromQuery = query?.endDate ? dayjs(query.endDate as string) : null

  // 如果 URL 中没有日期参数，则默认选择最近一年的时间范围
  if (!startDateFromQuery || !endDateFromQuery) {
    const oneMonthAgo = dayjs().subtract(30, 'day').startOf('day')
    const today = dayjs().endOf('day')

    form.value.date = [oneMonthAgo.toDate(), today.toDate()]
    form.value.start_date = oneMonthAgo.format('YYYY-MM-DD')
    form.value.end_date = today.format('YYYY-MM-DD')
  } else {
    form.value.date = [startDateFromQuery.toDate(), endDateFromQuery.toDate()]
    form.value.start_date = startDateFromQuery.format('YYYY-MM-DD')
    form.value.end_date = endDateFromQuery.format('YYYY-MM-DD')
  }

  form.value.model_id = query?.model_id ? Number(query?.model_id) : ''
  form.value.seller_id = query?.seller_id ? [Number(query?.seller_id)] : []

  getDropDownBoxInfo()
  if (form.value.model_id) {
    initLine()
  }
})
</script>

<style lang="less" scoped>
.table-container {
  width: 50%;

  /* 根据需求设置宽度 */
  height: auto;

  /* 自动调整高度以适应内容 */
  max-height: 30%;

  /* 为了确保不会溢出视图，可设置最大高度 */
  //position: relative; /* 使用绝对定位 */
  //left: 60%; /* 右边距设置为0，贴紧右侧 */
  min-width: 400px;
  overflow: auto;

  /* 当内容太长时可以滚动 */
}
</style>
